<template>
	<uv-upload :fileList="fileList" :name="formDataName" multiple :maxCount="limit" :accept="accept"
		:disabled="disabled" @afterRead="afterRead" @delete="deletePic"></uv-upload>
</template>

<script lang="ts" setup>
	import { ref, watch } from "vue";
	import { useAppStore } from "@/store";
	import { getToken } from '@/utils/auth';

	const emit = defineEmits(["update:modelValue"]);
	const props = defineProps({
		modelValue: {
			type: Array,
			default: [],
		},
		disabled: {
			type: Boolean,
			default: false,
		},
		limit: {
			type: Number,
			default: 1
		},
		formDataName: {
			type: String,
			default: 'file'
		},
		accept: {
			type: String,
			default: 'image'
		}
	})

	const fileList = ref<any>([]);
	const limit = ref(props.limit);
	const disabled = ref(props.disabled);
	const formDataName = ref(props.formDataName);
	const accept = ref(props.accept);

	const resultList = ref<any>(props.modelValue);
	const appStore = useAppStore();

	// 删除图片
	const deletePic = (event : any) => {
		fileList.value.splice(event.index, 1)
		resultList.value.splice(event.index, 1)
	}

	// 新增图片
	const afterRead = async (event : any) => {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListLen = fileList.value.length
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url)
			let item = fileList.value[fileListLen]
			fileList.value.splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: result
			}));
			resultList.value.splice(fileListLen, 1, result);
			fileListLen++
		}
	}

	const uploadFilePromise = (url : string) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${appStore.baseUrl}/file/upload`,
				filePath: url,
				name: 'file',
				header: {
					'Authorization': 'Bearer ' + getToken()
				},
				success: (res) => {
					setTimeout(() => {
						resolve(JSON.parse(res.data).data)
					}, 1000)
				}
			});
		})
	}

	watch(
		() => resultList.value,
		(newVal) => {
			emit("update:modelValue", newVal);
		},
		{ deep: true }
	);

	watch(
		() => props.modelValue,
		(newVal) => {
			fileList.value = newVal.map((item) => {
				return {
					url: appStore.baseUrl + item
				}
			})
			resultList.value = newVal;
		},
		{ deep: true }
	);
</script>